const { message, Select, Form, Input, Button } = antd;
const { useState } = React;

const days = Array.from({ length: 7 }, (_, index) => index).map(item => (
    <Select.Option key={item} value={item + 1}>
        {item + 1}
    </Select.Option>
));

const parseWeekStrToArray = str => {
    return new Promise((resolve, reject) => {
        const days = str.split(/,|，/).filter(Boolean);

        resolve(
            days
                .map(item => {
                    if (item.indexOf('-') !== -1) {
                        var [start, end] = item.split('-').slice(0, 2);
                        console.log(start, end);
                        if (start === '') {
                            start = 1;
                        }
                        if (end === '') {
                            end = 20;
                        }

                        start = Number.parseInt(start);
                        end = Number.parseInt(end);
                        if (Number.isNaN(start) || Number.isNaN(end)) {
                            reject(`异常字符 "${item}"，请输入"数字"和",，"的组合`);
                            return;
                        }

                        if (end > 20) {
                            reject(`"${item}" 大于20，请输入低于20以下的数字`);
                            return;
                        }
                        let result = [];
                        for (let i = start; i <= end; i++) {
                            result.push(i);
                        }
                        return result;
                    } else {
                        let result = Number.parseInt(item);
                        if (Number.isNaN(result)) {
                            reject(`异常字符 "${item}"，请输入"数字"和",，"的组合`);
                            return;
                        }
                        if (result > 20) {
                            reject(`"${item}" 大于20，请输入低于20以下的数字`);
                            return;
                        }
                        return result;
                    }
                })
                .flat(Infinity)
        );
    });
};

function Load() {
    const { loading: loadingOfTeacherList, data: teacherList = [] } = useRequest(
        () => {
            return new Promise(resolve => {
                request
                    .get('/teacher/teacherList')
                    .then(res => {
                        console.log(res);
                        resolve(Array.isArray(res) ? res : []);
                    })
                    .catch(err => {
                        resolve([]);
                        message.error(err.message);
                        console.log(err);
                    });
            });
        },
        {
            manual: false,
        }
    );
    const { loading: loadingOfClassList, data: classList = [] } = useRequest(
        () => {
            return new Promise(resolve => {
                request
                    .get('/class/classList')
                    .then(res => {
                        console.log(res);
                        resolve(Array.isArray(res) ? res : []);
                    })
                    .catch(err => {
                        resolve([]);
                        message.error(err.message);
                        console.log(err);
                    });
            });
        },
        {
            manual: false,
        }
    );
    const { loading: loadingOfCourseList, data: courseList = [] } = useRequest(
        () => {
            return new Promise(resolve => {
                request
                    .get('/course/courseList')
                    .then(res => {
                        console.log(res);
                        resolve(Array.isArray(res) ? res : []);
                    })
                    .catch(err => {
                        resolve([]);
                        message.error(err.message);
                        console.log(err);
                    });
            });
        },
        {
            manual: false,
        }
    );
    const { loading: loadingOfClassRoomList, data: classRoomList = [] } = useRequest(
        () => {
            return new Promise(resolve => {
                request
                    .get('/classroom/classroomList')
                    .then(res => {
                        console.log(res);
                        resolve(Array.isArray(res) ? res : []);
                    })
                    .catch(err => {
                        resolve([]);
                        message.error(err.message);
                        console.log(err);
                    });
            });
        },
        {
            manual: false,
        }
    );

    const { loading: addScheduleLoading, run: addSchedule } = useRequest(
        values => {
            return new Promise(resolve => {
                parseWeekStrToArray(values.week).then(week => {
                    request
                        .get(
                            `/classSchedule/addSchedule?${qs.stringify({
                                ...values,
                                week: week,
                            })}`
                        )
                        .then(res => {
                            console.log(res);
                            if (typeof res === 'boolean') {
                                if (res) {
                                    message.success('添加成功');
                                } else {
                                    message.error('添加失败，请检查是否有课程冲突');
                                }
                            } else {
                                message.error('服务器出现错误');
                            }
                        })
                        .catch(err => {
                            message.error(err.message);
                            console.log(err);
                        });
                });
            });
        },
        {
            manual: true,
        }
    );

    return (
        <div style={{ display: 'flex', flexDirection: 'column', justifyContext: 'center', alignItems: 'center' }}>
            <h1>添加课表</h1>
            <Form
                onFinish={values => {
                    addSchedule(values);
                }}
                layout='vertical'
                style={{ width: 300 }}>
                <Form.Item label='教师' name='teacherId' rules={[required('请输入教师')]}>
                    <Select>
                        {teacherList.map(item => (
                            <Select.Option key={item.no} value={item.no}>
                                {item.name}
                            </Select.Option>
                        ))}
                    </Select>
                </Form.Item>
                <Form.Item label='班级' name='classId' rules={[required('请输入班级')]}>
                    <Select>
                        {classList.map(item => (
                            <Select.Option key={item.id} value={item.id}>
                                {item.id}
                            </Select.Option>
                        ))}
                    </Select>
                </Form.Item>
                <Form.Item label='课程' name='courseId' rules={[required('请输入课程')]}>
                    <Select>
                        {courseList.map(item => (
                            <Select.Option key={item.id} value={item.id}>
                                {item.name}
                            </Select.Option>
                        ))}
                    </Select>
                </Form.Item>

                <Form.Item label='教室' name='classroomId' rules={[required('请输入教室')]}>
                    <Select>
                        {classRoomList.map(item => (
                            <Select.Option key={item.id} value={item.id}>
                                {item.name}@{item.position}
                            </Select.Option>
                        ))}
                    </Select>
                </Form.Item>

                <Form.Item
                    label='周'
                    name='week'
                    rules={[
                        required('请输入周次'),
                        {
                            validateTrigger: 'submit',
                            validator(_, value) {
                                return parseWeekStrToArray(value);
                            },
                        },
                    ]}>
                    <Input />
                </Form.Item>

                <Form.Item label='天' name='day' rules={[required('请输入星期')]}>
                    <Select>{days}</Select>
                </Form.Item>

                <Form.Item label='节' name='section' rules={[required('请输入节')]}>
                    <Select>
                        <Select.Option key='1' value={1}>
                            第一节
                        </Select.Option>
                        <Select.Option key='3' value={3}>
                            第二节
                        </Select.Option>
                        <Select.Option key='5' value={5}>
                            第三节
                        </Select.Option>
                        <Select.Option key='7' value={7}>
                            第四节
                        </Select.Option>
                    </Select>
                </Form.Item>

                <Form.Item>
                    <Button type='primary' htmlType='submit'>
                        提交
                    </Button>
                </Form.Item>
            </Form>
        </div>
    );
}
